package filters

import (
	"fmt"
	"log"
	"loghub/db"
	"loghub/model"
	"time"

	"github.com/kataras/iris/v12"
)

// AuthHandle 授权中间件
func AuthHandle(ctx iris.Context) {
	// 判断用户是否登录
	var sid = ctx.GetCookie("sid")
	if len(sid) <= 0 {
		// 重定向到首页
		ctx.Redirect("/")
	}
	var userSession = model.UserSession{}
	var sql = "select * from user_session where sid='%s'"
	var querystring = fmt.Sprintf(sql, sid)
	err := db.QueryStructByReflect(querystring, &userSession)
	if err != nil {
		log.Println(err)
	}
	if userSession.Sid == sid && int(time.Now().Sub(userSession.CreateTime).Seconds()) < userSession.ExpireTime {
		// fmt.Println("当前登录有效")
		ctx.Values().Set("user", userSession)
		ctx.NextOrNotFound()
	} else {
		log.Println("登录已过期")
		ctx.Redirect("/")
	}
}
